<template>
  <div class='container'>
    <div class="app-container">
      <el-card>
        <p>{{title}}</p>
        <el-divider></el-divider>
        <el-form label-width="100px" ref="addForm" :model="list" :rules="rules">
          <el-form-item label="学科 :" prop="subjectID">
            <el-select placeholder="请选择" v-model="list.subjectID" class="input" @blur="question('subjectID')">
              <el-option
              v-for="(item,index) in subject"
              :key="index"
              :label="item.label"
              :value="item.value"
              @click.native="getCatalog()"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录 :" prop="catalogID">
            <el-select placeholder="请选择" class="input" v-model="list.catalogID" @blur="question('catalogID')">
              <el-option
                v-for="item in catalog"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业 :" prop="enterpriseID">
            <el-select placeholder="请选择" class="input" v-model="list.enterpriseID" @blur="question('enterpriseID')">
              <el-option
              v-for="item in companys"
              :key="item.id"
              :label="item.company"
              :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市 :" prop="province">
            <el-select placeholder="请选择" v-model="list.province" style="margin-right:5px; width:200px" @blur="question('province')">
              <el-option
              v-for="(item,index) in provinces"
              :key="index"
              :label="item"
              :value="item"
              @click.native="getProvinces"
              >
              </el-option>
            </el-select>
            <el-select placeholder="请选择" v-model="list.city" style="width:195px">
              <el-option
              v-for="(item,index) in citys"
              :key="index"
              :label="item"
              :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向 :" prop="direction">
            <el-select placeholder="请选择" class="input" v-model="list.direction" @blur="question('direction')">
              <el-option
              v-for="(item,index) in directionList"
              :key="index"
              :label="item"
              :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型 :">
            <el-radio-group v-model="list.questionType">
              <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value+''"
              >{{item.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度 :" >
            <el-radio-group v-model="list.difficulty" >
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="item.value+''"
               >{{item.label}}
               </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干 :" prop="question">
            <quill-editor :options="editorOption" v-model="list.question" class="editor" @blur="question('question')"></quill-editor>
          </el-form-item>
          <el-form-item label="选项 :" v-if="list.questionType !== '3'">
            <div class="option" v-for="(item,index) in list.options" :key="index">
              <el-radio v-if="list.questionType === '1'" v-model="item.isRight" :label="true" @change="radio(item)">{{item.code}}：</el-radio>
              <el-checkbox v-if="list.questionType === '2'" v-model="item.isRight" :label="true" >{{item.code}}：</el-checkbox>
              <el-input style="width:250px; margin-right:3px" v-model="item.title"></el-input>
              <el-upload
                drag
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :headers="{'Authorization' : 'Bearer ' + token}"
                :show-file-list="false"
                :on-success="(res,file)=> {return handleAvatarSuccess(item,res,file)}"
                >
                <img v-if="item.img" :src="item.img" class="avatar">
                <span v-else class="el-upload__text">上传图片</span>
              </el-upload>
              <i class="el-icon-circle-close" @click="delUpload(index)"></i>
            </div>
            <el-button type="danger" :disabled="isdisabled()" @click="addOption">+增加选项与答案</el-button>
          </el-form-item>
          <el-form-item label="解析视频 :" >
            <el-input v-model="list.videoURL" class="input"></el-input>
          </el-form-item>
          <el-form-item label="答案解析 :" prop="answer">
            <quill-editor :options="editorOption" class="editor" v-model="list.answer" @blur="question('answer')"></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注 :">
            <el-input type="textarea" :rows="5" class="input" v-model="list.remarks"></el-input>
          </el-form-item>
          <el-form-item label="试题标签 :" >
            <el-select
            class='a'
            placeholder="请选择标题标签"
            multiple
            v-model="list.tags"
            >
            <el-option
            v-for="item in tags"
            :key="item.value"
            :label="item.label"
            :value="item.label"
            ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="!list.id" type="primary" size="small" @click="clickSubmit">确定提交</el-button>
            <el-button v-else type="success" size="small" @click="clickUpdate">确定修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/directorys.js'
import { list as companys } from '@/api/hmmm/companys.js'
import { direction, status, questionType, difficulty } from '@/api/hmmm/constants.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as tags } from '@/api/hmmm/tags.js'
import { getToken } from '@/utils/auth.js'
import { add, update, detail } from '@/api/hmmm/questions.js'

export default {
  name: 'Questions-New',
  data () {
    return {
      token: getToken(),
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块、链接、图片、视频
          ] // 工具菜单栏配置
        },
        placeholder: ''
      },
      list: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', img: '', title: '', isRight: false },
          { code: 'B', img: '', title: '', isRight: false },
          { code: 'C', img: '', title: '', isRight: false },
          { code: 'D', img: '', title: '', isRight: false }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ], // 学科
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ], // 目录
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ], // 企业
        province: [
          { required: true, message: '请选择地区', trigger: ['blur', 'change'] }
        ], // 地区
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ], // 方向
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ], // 题干
        answer: [
          { required: true, message: '请输入题目解析', trigger: ['blur', 'change'] }
        ] // 解析
      },
      subject: [],
      catalog: [],
      companys: [],
      directionList: direction,
      provinces: [],
      citys: [],
      tags: [],
      status,
      questionType,
      difficulty,
      fileList: [],
      imgUpload: true
    }
  },
  computed: {
    title () {
      return this.list.id ? '试题修改' : '试题录入'
    }
  },
  created () {
    this.getSubject()
    this.getcompanys()
    this.provinces = provinces()
    if (this.$route.query.id) {
      this.getUpdateInfo()
    }
  },
  methods: {
    async getSubject () {
      const { data: res } = await simple()
      this.subject = res
    },
    async getCatalog () {
      const { data: { items } } = await list({ subjectID: this.list.subjectID })
      const { data: res } = await tags({ subjectID: this.list.subjectID })
      this.tags = res
      this.catalog = items
    },
    async getcompanys () {
      const { data: { items } } = await companys()
      this.companys = items
    },
    ww () {

    },
    getProvinces () {
      this.list.city = ''
      this.citys = citys(this.list.province)
    },
    handleAvatarSuccess (item, res, file) {
      item.img = URL.createObjectURL(file.raw)
    },
    isdisabled () {
      if (this.list.questionType === '1') {
        return true
      } else {
        return false
      }
    },
    radio (obj) {
      this.list.options.forEach(item => { item.isRight = false })
      obj.isRight = true
    },
    addOption () {
      this.list.options.push({
        code: String.fromCharCode(65 + this.list.options.length),
        img: '',
        title: '',
        isRight: ''
      })
    },
    question (res) {
      this.$refs.addForm.validateField(res)
    },
    clickSubmit () {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return
        const data = { ...this.list }
        data.tags = data.tags.join(',')
        console.log(data)
        await add(data)
        this.$message.success('试题录入成功')
        this.$router.push('/questions/list')
      })
    },
    async getUpdateInfo () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      // 返回数据isRight 是1的返回true 不是返回false
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.list = data
      this.getCatalog()
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    async clickUpdate () {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return
        const data = { ...this.list }
        data.tags = data.tags.join(',')
        await update(data)
        this.$message.success('试题修改成功')
        this.$router.push('/questions/list')
      })
    },
    delUpload (index) {
      if (index > 3) {
        this.list.options.splice(index, 1)
      } else {
        this.$message.error('默认选项不能删除')
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.app-container {
  .editor {
      line-height: normal !important;
      height: 200px;
      margin-bottom: 45px;
  }
  .option{
      width: 400px;
      height: 60px;
      display: flex;
      justify-content:flex-start;
      align-items: center;
      margin-bottom: 10px;
      position: relative;
    ::v-deep {
      .avatar-uploader {
      display: inline-block;
      vertical-align: middle;
      line-height: 1;
      position: relative;
      }
      .el-radio{
        margin-right: 3px;
      }
      .el-upload-dragger {
        width: 100px;
        height: 60px;
        margin-top: 10px;
      }
      .el-upload__text {
        position: absolute;
        width: 60px;
        height: 60px;
        line-height: 60px;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
      }
      i{
        position: absolute;
        right: -9px;
        top: -5px;
        font-size: 20px;
        color: #ccc;
      }
      .avatar {
        width: 100%;
        height: 100%;
      }
    }
  }
  .input {
    width: 400px;
  }
}
</style>
